package ohttp

import (
	"net"
	"strconv"

	"gitee.com/cooge/impush/core"
	"gitee.com/cooge/impush/message"
	user2 "gitee.com/cooge/impush/user"
	"gitee.com/cooge/impush/util"
	"gitee.com/cooge/impush/xhttp/user"
)

type OHttpConn struct {
	*user.HttpConn
	deadlineTime int
}

func NewOHttpConn(conn net.Conn) *OHttpConn {
	return &OHttpConn{HttpConn: &user.HttpConn{UserLite: &user2.UserLite{UserTCPConn: conn, Type: message.HTTP, Local: true}}}
}

func (ohc *OHttpConn) Start(dealTime int, livetime int, userId string, cnc user.CallNewConnFunc) {
	ohc.HttpConn.HttpConnWrite = ohc.write
	ohc.HttpConn.HttpConnFlush = ohc.Flush
	ohc.CreateTime = util.GetNowTime()
	ohc.Deadline = dealTime
	ohc.LiveTime = livetime + livetime
	ohc.UserId = userId
	go ohc.read()
	cnc(ohc)
}

func (ohc *OHttpConn) read() {
	ohc.HttpConn.Add()
	da := make([]byte, 1)
	ohc.Read(da)
	ohc.Close(ohc.UserId)
}
func (ohc *OHttpConn) Flush() {
	if ohc.IsTimeOut() {
		core.DeleteUser(ohc.UserId, ohc.HttpConn)
	} else {
		if !ohc.IsBreak() {
			ohc.write([]byte(`[]`))
		}
	}
	ohc.Close(ohc.UserId)
}
func (ohc *OHttpConn) write(data []byte) (int, error) {
	ln := len(data)
	var header string = "HTTP/1.1 200 OK\r\n" +
		"Content-Type: text/html;charset=UTF-8\r\n" +
		"Content-Language: zh\r\n" +
		"Access-Control-Allow-Origin: *\r\n" +
		"Content-Length: " + strconv.Itoa(ln) + "\r\n\r\n"
	da := make([]byte, 0)
	buf := []byte(header)
	da = append(da, buf...)
	da = append(da, data...)
	num, err := ohc.Write(da)
	ohc.Close(ohc.UserId)
	return num, err
}
